import time
import json
import random
import logging
from typing import List, Optional
from coolApkAPI import coolApkAPI

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 全局变量记录已使用的回复和最后使用时间
used_replies = []
last_reset_time = time.time()

def load_replies(file_path: str = 'replyText.json') -> List[str]:
    """加载回复文本列表"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)["universal_replies"]
    except (FileNotFoundError, json.JSONDecodeError, KeyError) as e:
        logger.error(f"加载回复文件失败: {str(e)}")
        return []
    except Exception as e:
        logger.error(f"加载回复时发生未知错误: {str(e)}")
        return []

def get_random_reply(reply_list: List[str]) -> Optional[str]:
    """获取随机回复，确保10分钟内不重复"""
    global used_replies, last_reset_time

    try:
        # 检查是否需要重置已用列表（超过10分钟）
        current_time = time.time()
        if current_time - last_reset_time > 600:  # 10分钟=600秒
            used_replies = []
            last_reset_time = current_time
            logger.info("已重置回复选择池")

        # 过滤掉已使用的回复
        available_replies = [reply for reply in reply_list if reply not in used_replies]

        if not available_replies:
            # 如果没有可用回复，重置已用列表
            used_replies = []
            available_replies = reply_list.copy()
            logger.info("所有回复已使用一遍，已重置选择池")

        # 随机选择一个回复
        selected = random.choice(available_replies)
        used_replies.append(selected)
        logger.info(f"选择回复: {selected[:20]}...")  # 只记录前20个字符

        return selected
    except Exception as e:
        logger.error(f"获取随机回复时出错: {str(e)}")
        return None

def safe_api_call(func, *args, **kwargs):
    """安全执行API调用，捕获所有异常"""
    try:
        return func(*args, **kwargs)
    except Exception as e:
        logger.error(f"API调用失败: {func.__name__}, 错误: {str(e)}")
        return None

if __name__ == '__main__':
    try:
        # 加载回复列表
        reply_texts = load_replies()
        if not reply_texts:
            raise RuntimeError("没有可用的回复文本")

        logger.info(f"加载了 {len(reply_texts)} 条回复文本")

        # 读取headers
        try:
            with open('headers.json', 'r', encoding='utf-8') as f:
                headers = json.load(f)
            logger.info("成功加载headers")
        except Exception as e:
            raise RuntimeError(f"加载headers失败: {str(e)}")

        # 初始化API
        api = coolApkAPI(headers)
        logger.info("API初始化成功")

        # 获取最新话题
        datalist = safe_api_call(api.dataList)
        if not datalist or "data" not in datalist:
            raise RuntimeError("获取话题列表失败")

        for data in datalist["data"]:
            try:
                # 只获取有效的帖子
                id = str(data.get("id")) if data.get("id") else None
                if not id:
                    continue

                # 提取标题
                message = data.get("message", "")
                title = message.split("</a>")[-1].replace("\n", "").strip() if "</a>" in message else message
                logger.info(f"处理帖子 编号{id}: {title[:30]}...")  # 只记录前30个字符

                # 点赞
                like_result = safe_api_call(api.posts_like, id)

                # 获取随机回复
                reply_text = get_random_reply(reply_texts)
                if not reply_text:
                    logger.warning("无法获取有效回复文本，跳过回复")
                    continue

                # 回复
                reply_result = safe_api_call(api.posts_reply, id, reply_text)

                # 间隔时间
                time.sleep(30)

            except Exception as e:
                logger.error(f"处理帖子 {id} 时出错: {str(e)}", exc_info=True)
                continue  # 继续处理下一个帖子

    except Exception as e:
        logger.critical(f"程序运行失败: {str(e)}", exc_info=True)
    finally:
        logger.info("程序运行结束")